package pers.burgess.fsm.client.gui;

import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class ClientGUI extends JFrame {
	
	private static final String CLIENT_NAME = "Burgess Bash";
	
	private static final int BASH_WIDTH = 1000;
	private static final int BASH_HEIGHT = 700;
	
	private static final Font DEFAULT_FONT = new Font("微软雅黑", 0, 16);
	
	private static final Color BACKGROUND_COLOR = Color.decode("#1565C0");
	private static final Color FOREGROUND_COLOR = Color.WHITE;
	
	private JTextArea bashArea = null;
	private BashListener bashListener = null;
	
	public ClientGUI () {
		super(CLIENT_NAME);
		
		this.setSize(BASH_WIDTH + 5, BASH_HEIGHT + 30);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setResizable(false);
		this.setLocationRelativeTo(null);
		
		initializeContainer();
	}
	
	private void initializeContainer () {
		Container container = this.getContentPane();
        container.setBackground(null);
        container.setLayout(null);
        
        this.bashArea = new JTextArea();
        bashArea.setSize(BASH_WIDTH,BASH_HEIGHT);
        bashArea.setBounds(0, 0, BASH_WIDTH, BASH_HEIGHT);
        bashArea.setBackground(BACKGROUND_COLOR);
        bashArea.setForeground(FOREGROUND_COLOR);
        bashArea.setCaretColor(FOREGROUND_COLOR);
        bashArea.setFont(DEFAULT_FONT);
        bashArea.setFocusable(true);
        

        JScrollPane pane = new JScrollPane(this.bashArea);
        pane.setBackground(null);
        pane.setBounds(0, 0, BASH_WIDTH, BASH_HEIGHT);
        
        this.bashArea.addKeyListener(new KeyListener() {

			public void keyTyped(KeyEvent e) {}

			public void keyPressed(KeyEvent e) {}

			public void keyReleased(KeyEvent e) {
				if (e.getKeyCode() == e.VK_ENTER && bashArea != null && bashListener != null) {
					String[] commands = bashArea.getText().split("\n");
					bashListener.newCommand(commands[commands.length-1].substring(commands[commands.length-1].lastIndexOf(">") + 1).trim());
				}
			}
			
		});
        
        container.add(pane);
	}
	
	public void setBashListener (BashListener bashListener) {
		this.bashListener = bashListener;
	}

	public void append(String str, boolean nextLine) {
		this.bashArea.append(str + " > " + (nextLine ? "\n" : ""));
		this.bashArea.setCaretPosition(this.bashArea.getText().length());
	}

	public BashListener getBashListener() {
		return bashListener;
	}
	
	
}
